const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
let config = require('../config')
// 注册
exports.reguser = (req, res) => {
    const userinfo = req.body
    if (!userinfo.userName || !userinfo.passWord) {
        return res.cc('用户名或者密码为空')
    }
    const sqlstr = 'select * from ev_users where username=?'
    db.query(sqlstr, userinfo.userName, (err, results) => { })
    userinfo.passWord = bcrypt.hashSync(userinfo.passWord, 10)
    const sql = 'insert into ev_users set ?'
    db.query(sql, { userName: userinfo.userName, passWord: userinfo.passWord }, (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.affectedRows !== 1) {
            return res.cc('注册失败,请稍后再试')
        }
        res.cc('注册成功', 0)
    })
}
// 登录
exports.login = (req, res) => {
    const userinfo = req.body
    console.log(userinfo, 'userinfo');
    console.log(config);

    const sql = 'select * from ev_users where userName=?'
    db.query(sql, [userinfo.userName], (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('登录失败')
        const count = bcrypt.compareSync(userinfo.passWord, results[0].passWord)
        if (!count) {
            return res.cc('登录失败')
        }
        // res.send(results)
        const user = { ...results[0], passWord: null, user_pic: null }
        const token = jwt.sign(user, config.jsonKey, { expiresIn: '10h' })
        res.send({
            message: '登录成功',
            token: 'Bearer ' + token
        })
    })
}